#!/usr/bin/wish

proc get_clipboard {} {
    # set contents [clipboard get]
    # set contents [selection get -selection CLIPBOARD]
    if {[catch {clipboard get} contents]} {
		# puts "no clipboard contents"
		return ""
    }
	# puts $contents
    return $contents
}

proc set_clipboard { str } {
	clipboard clear
	clipboard append $str
}

proc every {ms body} {
	eval $body
	after $ms [info level 0];   # the name of this proc (here is every)
}

# proc send_str { str } {
# 	set_clipboard $str
# 	every 1000 {if {[get_clipboard]=="OK"} return}
# }




set recv_line_cnt 0

proc recv_file { } {
    global recv_fileid
    global recv_line_cnt
    set contents [get_clipboard]
    if { $contents == "" } {
	return
    } elseif { $contents == "END" } {
	close $recv_fileid
	exit
    } elseif { $contents != "OK" } {
	puts -nonewline $recv_fileid $contents
	puts "receive line $recv_line_cnt"
	set_clipboard "OK"
	incr recv_line_cnt
    }
}

set send_state 0
set send_line_cnt 0
proc send_file { } {
	global send_state
	global send_line_cnt
	global send_fileid
	if { $send_state == 0 } {		# send string
		if { [gets $send_fileid line] >= 0 } {
			set_clipboard $line
		} else {
			set_clipboard "END"
			set send_line_cnt "END"
			# exit
		}
		set send_state 1
	} else {					# get response
		puts "wait response $send_line_cnt"
		if {[get_clipboard]=="OK"} {
			if { $send_line_cnt == "END" } {
				puts "finished"
				exit
			} else {
				incr send_line_cnt
				set send_state 0	
			}
		}
	}
}



proc usage_exit {} {
	puts "# usage :
# ./trans.tcl send result.txt
# ./trans.tcl recv recv.txt"
	exit
}

if {[llength $argv]!=2} {
	usage_exit
}

if {[lindex $argv 0] == "send"} {
	set send_fileid [open [lindex $argv 1]]
	every 1000 {send_file}
} elseif {[lindex $argv 0] == "recv"} {
    set recv_fileid [open [lindex $argv 1] "w"]
    clipboard clear
    puts "please start the sender"
    every 1000 {recv_file}
} else {
	usage_exit
}

